<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Folder;
use app\api\model\v1\GatherFile;
use app\api\model\v1\ProjectDetail;
use app\api\model\v1\ProjectSample;
use app\api\model\v1\ProjectSecondLevel;
use app\api\model\v1\ProjectType;
use app\api\model\v1\WxLog;
use app\api\validate\v1\SampleValidate;
use app\BaseController;
use think\Env;
use think\exception\ValidateException;
use think\Request;

class DataCenter extends BaseController
{

    use FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/11/12
     * @Time: 10:56
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据项目id获取对应的一级指标
     */
    public function getProjectTypeList()
    {
        $project_id = $this->request->param('project_id');
        $res = ProjectType::where(['project_id' => $project_id])->select()->toArray();
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/12
     * @Time: 11:00
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据项目一级指标获取对应的样本点
     */
    public function getProjectSampleList()
    {
        $project_type_id = $this->request->param('project_type_id');
        $res = ProjectSample::where(['project_type_id' => $project_type_id])->select()->toArray();
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/12
     * @Time: 15:06
     * @return \think\response\Json
     * 自定义创建样本点
     */
    public function customCreateSample()
    {
        $data = $this->request->param();
        try {
            $validator = $this->validate($data, SampleValidate::rules(), SampleValidate::msg());
            if ($validator) {
                $data['create_id'] = $this->request->wx_id;
                $sample_id = ProjectSample::create($data)->id;
                //微信端操作日志
                WxLog::record('新增自定义样本点', $data, $this->request->wx_id);
                return $this->response(['sample_id' => $sample_id]);
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->response(403, $e->getError());
        }
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/11/12
     * @Time: 15:26
     * @return \think\response\Json
     * 创建文件夹
     */
    public function createProjectFolder()
    {
        $data = $this->request->param();
        $title_arr = explode('@', $data['title']);
        $res = Folder::create([
            'title' => $title_arr[0] ?? '',
            'sub_title' => $title_arr[1] ?? '',
            'project_id' => $data['project_id'],
            'project_type_id' => $data['project_type_id'],
            'project_sample_id' => $data['project_sample_id'],
            'create_id' => $this->request->wx_id,
        ]);
        //微信端操作日志
        WxLog::record('新增文件夹', $data, $this->request->wx_id);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/12
     * @Time: 15:32
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取文件夹列表
     */
    public function getProjectFolderList()
    {
        $project_id = $this->request->param('project_id');
        $res = Folder::with(['user'])->where(['project_id' => $project_id,'create_id'=>$this->request->wx_id])->order(['create_time' => 'desc'])->select()->each(function ($item, $key) {
            $item['nickname'] = $item['user']['nickname'];
            return $item;
        })->toArray();
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/11/15
     * @Time: 9:15
     * @return \think\response\Json
     * 保存照片
     */
    public function saveImg()
    {
        $type= $this->request->param('type','camera'); //默认相机
        $file = $this->request->file('file');
        $result = $this->save($file, 'gather_img');
        $result['equipment'] = json_decode($this->request->param('equipment'), true);
        //微信端操作日志
        WxLog::record($type == 'upload' ? '上传照片' : '相机拍摄上传', $result, $this->request->wx_id);
        return $this->response($result);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/15
     * @Time: 9:49
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存文件上传
     */
    public function saveGatherFileImg()
    {
        $data = $this->request->param();
        $folder = Folder::find(intval($data['folder_id']));
        $type = $this->request->param('type','upload');
        if (is_null($folder)) {
            return $this->response(403, '暂未找到当前文件夹');
        }
        $img_arr = explode(',', $data['str_img']);
        $new_data = [];
        foreach ($img_arr as $key => $value) {
            $new_data[$key]['user_id'] = $this->request->wx_id ?? 0;
            $new_data[$key]['url'] = $value ?? '';
            $new_data[$key]['project_id'] = $folder['project_id'] ?? 0;
            $new_data[$key]['project_type_id'] = $folder['project_type_id'] ?? 0;
            $new_data[$key]['project_sample_id'] = $folder['project_sample_id'] ?? 0;
            $new_data[$key]['longitude'] = $data['longitude'] ?? '';
            $new_data[$key]['latitude'] = $data['latitude'] ?? '';
            $new_data[$key]['folder_id'] = $data['folder_id'] ?? 0;
        }
        $gather = new GatherFile();
        $gather->saveAll($new_data);
        WxLog::record($type == 'camera' ? '拍摄保存文件上传' : '选择保存文件上传', $data, $this->request->wx_id);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/15
     * @Time: 10:02
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 文件夹照片库
     */
    public function getPhotoFolderList()
    {
        $limit = $this->request->param('limit');
        $folder_id = intval($this->request->param('folder_id'));
        $isAllotActive = $this->request->request('isAllotActive');
        $map = [];
        if (intval($isAllotActive) === 1) {
            $map[] = ['is_allot', '=',GatherFile::IS_ALLOT_ZERO]; //未分配
        } else {
            $map[] = ['is_allot', '=', GatherFile::IS_ALLOT_ONE]; //已分配
        }
        $map[] = ['folder_id', '=', $folder_id];
        $map[] = ['user_id', '=', $this->request->wx_id];
        $res = GatherFile::with(['user', 'folder', 'project', 'projectType', 'projectSample','projectSecond','projectDetail'])->where($map)->order(['create_time' => 'desc'])->paginate($limit)->each(function ($item,$key){
            $item['show'] = '';
            return $item;
        });
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/15
     * @Time: 14:25
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据条件获取对应的二级指标
     */
    public function getProjectSecondLevelList()
    {
        $data = $this->request->param();
        $res = ProjectSecondLevel::with(['extra'])->where(['project_id' => $data['project_id'], 'project_type_id' => $data['project_type_id']])->select()->toArray();
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/15
     * @Time: 15:26
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存分配指标
     */
    public function saveAllotGather()
    {
        $data = $this->request->param();
        $gather = GatherFile::find(intval($data['id']));
        if (is_null($gather)) {
            return $this->response(403, '暂未找到该采集信息');
        }
        $data['is_allot'] = GatherFile::IS_ALLOT_ONE;
        WxLog::record('分配指标', $data, $this->request->wx_id);
        $gather->save($data);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/22
     * @Time: 10:54
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 重新分配指标
     */
    public function againSaveAllotGather()
    {
        $data = $this->request->param();
        $gather = GatherFile::find(intval($data['id']));
        if (is_null($gather)) {
            return $this->response(403, '暂未找到该采集信息');
        }
        WxLog::record('重新分配指标', $data, $this->request->wx_id);
        $gather->save($data);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/22
     * @Time: 14:57
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 批量分配指标
     */
    public function operationSaveGather(){
        $data = $this->request->param();
        $type = $this->request->param('type','wx');
        $id_arr = explode(',',$data['ids']);
        foreach ($id_arr as $key=>$value){
            $gather = GatherFile::find(intval($value));
            if (is_null($gather)){
                return $this->response(403,'暂未找到该数据');
            }
            $data['is_allot'] = GatherFile::IS_ALLOT_ONE; //已分配
            $gather->save($data);
            if ($type === 'wx'){
                WxLog::record('WX端批量分配指标', $data, $this->request->wx_id);
            }else{
                AdminLog::record('PC端批量分配指标', $data, $this->request->uid,$this->request->username);
            }

        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/22
     * @Time: 16:02
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 复用保存采集信息
     */
    public function reuseSaveGather(){
        $data = $this->request->param();
        $gather = GatherFile::find(intval($data['old_id']));
        if (is_null($gather)){
            return $this->response(403,'暂未找到该数据');
        }
        $data['url'] = $gather['url'];
        $data['user_id'] = $this->request->wx_id;
        $data['folder_id'] = $gather['folder_id'];
        $data['is_allot'] = GatherFile::IS_ALLOT_ONE; //未分配
        GatherFile::create($data);
        WxLog::record('复用分配指标', $data, $this->request->wx_id);
        return $this->response();
    }
}
